package com.xiehua.task.persistence.rocks;

import com.xiehua.task.job.pool.DelayJob;
import com.xiehua.task.job.pool.Job;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;

public class RocksPool {

    private static final Logger logger = LoggerFactory.getLogger(RocksPool.class);

    private static GenericObjectPool<XeihuaPersitence> innerPool;


    private RocksPool(){

    }

    public static GenericObjectPool<XeihuaPersitence> getInstance() {
        if (innerPool == null) {
            synchronized (RocksPool.class) {
                if (innerPool == null) {
                    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig ();
                    poolConfig.setMaxTotal(20);
                    innerPool = initRocksPool(poolConfig,new RocksFactory());
                }
            }
        }
        return innerPool;
    }

    private static GenericObjectPool<XeihuaPersitence> initRocksPool(final GenericObjectPoolConfig poolConfig, PooledObjectFactory<XeihuaPersitence> factory){
        if(innerPool != null){
            logger.warn("innerPool is not null,destroy it..");
            innerPool.close();
        }
        return new GenericObjectPool<>(factory,poolConfig);
    }

    public static void main(String[] args) throws Exception{
        GenericObjectPool<XeihuaPersitence> pool = RocksPool.getInstance();
        for(int i =0;i< 1000;i++){
            XeihuaPersitence persitence = pool.borrowObject();
            Job job = new DelayJob();
            job.setStatus(Job.JobStatus.ready);
            job.setTopic("test------");
            persitence.persistence(job);
            pool.returnObject(persitence);
        }

    }
}
